package com.java.test.springbootminio.utils;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.RemoveBucketArgs;
import io.minio.messages.Bucket;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @since 2022/10/14 上午11:36
 */
@Component
public class MinioBucketUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(MinioBucketUtil.class);
    private MinioClient minioClient;

    @Autowired
    public void setMinioClient(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    /**
     * Bucket exists boolean.
     *
     * @param bucketName the bucket name
     * @return the boolean
     */
    public boolean bucketExists(String bucketName) {
        boolean found = false;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            LOGGER.error("Check bucket exists meet error.", e);
        }

        return found;
    }

    /**
     * Make bucket boolean.
     *
     * @param bucketName the bucket name
     * @return the boolean
     */
    public boolean makeBucket(String bucketName) {
        if (bucketExists(bucketName)) {
            return true;
        }

        try {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            LOGGER.error("Make bucket exists meet error.", e);
            return false;
        }

        return true;
    }

    /**
     * Remove bucket boolean.
     *
     * @param bucketName the bucket name
     * @return the boolean
     */
    public boolean removeBucket(String bucketName) {
        if (!bucketExists(bucketName)) {
            return true;
        }

        try {
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            LOGGER.error("Remove bucket exists meet error.", e);
            return false;
        }

        return true;
    }

    /**
     * Get all buckets list.
     *
     * @return the list
     */
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            LOGGER.error("List buckets meet error.", e);
        }

        return null;
    }

    /**
     * List bucket names list.
     *
     * @return the list
     */
    public List<String> listBucketNames() {
        final List<Bucket> allBuckets = getAllBuckets();
        if (Objects.isNull(allBuckets)) {
            return null;
        }

        return allBuckets.stream().map(Bucket::name).collect(Collectors.toList());
    }
}
